<template>
  <view class="container">
    <uv-navbar title="域名列表" :autoBack="true" ></uv-navbar>
    <!-- 加载动画 -->
    <gb-loading :loadGif="loadGif" v-if="loading && filteredTableData.length === 0"></gb-loading>
    <view>
      <tableCard :domain="item" v-for="(item,index) in tableData" :key="index" @clicked="handlerOption"></tableCard>
    </view>
    <!-- 删除确认框 -->
    <view v-if="showDeleteConfirm" class="delete-confirm-overlay">
      <view class="delete-confirm-container">
        <text class="delete-confirm-title">删除确认</text>
        <text class="delete-confirm-text">确定要删除这条记录吗？此操作无法撤销。</text>
        <view class="delete-confirm-buttons">
          <button @click="cancelDelete" class="form-button cancel-button">取消</button>
          <button @click="confirmDelete" class="form-button confirm-button">删除</button>
        </view>
      </view>
    </view>
  </view>
  <uv-toast ref="toast"></uv-toast>
</template>

<script setup>
import {onMounted, ref} from 'vue';
import {onNavigationBarButtonTap,onShow} from '@dcloudio/uni-app';
import tableCard from '@/components/card-all/tableCard.vue'
import {show} from '@/utils/index.js';
import {jumpPage} from '@/utils/uniUtil.js'
import {createDameRed, delDameRed, getDameRed, updateDameRed} from '@/api/app.js';

const loadGif = "/static/loading.gif";
const isnothing = ref(false);
const hasMore = ref(true);
const loading = ref(true);
const tableData = ref([]);
const showAddForm = ref(false);
const showEditForm = ref(false);
const showDeleteConfirm = ref(false);
const selectedIndex = ref(null);
const editItem = ref({});
const toast = ref()
const filteredTableData = ref([]);


onNavigationBarButtonTap((e) => {
  if (e.index === 0) { // 第一个按钮（索引从0开始）
    showAddForms()
  }
});

const handlerOption = (type,id) => {
  console.log('点击了按钮', type,id);
  if (type === 'edit'){
    jumpPage('/pages/home/form/domain',{type:'edit',id:id})
    return
  }
  if (type === 'del'){
    delDameRed(id).then(res=>{
      console.log(res)
      toast.value.show({
        message: res.msg,
        type: 'success',
        duration: 2000,
      })
    })
  }
}

// 加载数据
const loadData = async () => {
  loading.value = true
  tableData.value = []
  try {
    const response = await getDameRed()
    console.log(response)
    tableData.value = response.data || []
  } catch (e) {
    console.error("加载数据失败:", e)
  } finally {
    loading.value = false
  }
}

// 加载更多数据
const loadMoreData = () => {
  if (!hasMore.value || loading.value) return;
  loading.value = true;
  // 模拟加载更多数据
  setTimeout(() => {
    hasMore.value = false; // 假设没有更多数据
    loading.value = false;
  }, 1000);
};

// 下拉刷新
const refreshData = () => {
  loading.value = true;
  isnothing.value = false;
  loadData();
  setTimeout(() => {
    uni.stopPullDownRefresh();
  }, 500);
};

// 显示添加表单
const showAddForms = () => {
  showAddForm.value = true;
  editItem.value = {};
};

// 保存添加
const saveAdd = async () => {
  if (!editItem.value.protocol) {
    show('请选择协议', 'none');
    return;
  }
  const {protocol, domain, sld, target, platform} = editItem.value;
  const newItem = {
    domain: `${protocol}://${domain}/${sld}`,
    sld,
    target: `${protocol}://${domain}/${sld}/page?target=${target}`,
    platform,
    create_time: new Date()
  };
  try {
    const response = await createDameRed(newItem);
    if (response) {
      tableData.value.push(newItem);
      filteredTableData.value.push(newItem);
      showAddForm.value = false;
      show('添加成功', 'success');
    } else {
      show('添加失败', 'none');
    }
  } catch (e) {
    console.error("添加失败:", e);
    show('添加失败，请检查网络或重试', 'none');
  }
};




// 保存修改
const saveEdit = async () => {
  if (selectedIndex.value === null) {
    show('修改失败，数据无效', 'none');
    return;
  }
  const {protocol, domain, sld, target, platform} = editItem.value;
  const updatedItem = {
    domain: `${protocol}://${domain}/${sld}`,
    sld,
    target: `${protocol}://${domain}/${sld}/page?target=${target}`,
    platform
  };
  try {
    const response = await updateDameRed(filteredTableData.value[selectedIndex.value].id, updatedItem);
    if (response) {
      filteredTableData.value[selectedIndex.value] = updatedItem;
      showEditForm.value = false;
      show('保存成功', 'success');
    } else {
      show('保存失败', 'none');
    }
  } catch (e) {
    console.error("保存失败:", e);
    show('保存失败，请检查网络或重试', 'none');
  }
};

// 确认删除
const confirmDelete = async () => {
  if (selectedIndex.value === null) {
    show('删除失败，数据无效', 'none');
    return;
  }
  try {
    const response = await delDameRed(filteredTableData.value[selectedIndex.value].id);
    console.log("response:" + response)
    if (response === "DameRed deleted") {
      tableData.value = tableData.value.filter(item => item.id !== filteredTableData.value[selectedIndex.value].id);
      filteredTableData.value = filteredTableData.value.filter(item => item.id !== filteredTableData.value[selectedIndex.value].id);
      showDeleteConfirm.value = false;
      show('删除成功', 'success');
    } else {
      show('删除失败', 'none');
    }
  } catch (e) {
    console.error("删除失败:", e);
    show('删除失败，请检查网络或重试', 'none');
  }
};

// 取消删除
const cancelDelete = () => {
  showDeleteConfirm.value = false;
};

// 生命周期钩子
onMounted(() => {
  loadData()
})

onShow(()=>{
  loadData()
})

</script>

<style lang="scss">
page{
  background-color: #f8f8f8 !important;
}
</style>
<style lang="scss" scoped>
.container {
  padding-bottom: calc(0.1rpx + env(safe-area-inset-bottom));
  padding-top: calc(var(--status-bar-height) + 44px); /* 状态栏 + 导航栏高度 */
}


</style>
